package red.internal.server.registry.handler;

import io.netty.channel.Channel;
import red.internal.core.handler.SenderListener;
import red.internal.core.message.RegistryMessage;
import red.internal.server.exception.RegistryStorageException;
import red.internal.server.registry.channel.RegistryChannelGroup;
import red.internal.server.registry.storage.RegistryStorage;


/**
 * @author Jin Zheng
 * @since 2019-05-11
 */
public class WatchRegistryHandler implements RegistryHandler
{
	private final RegistryChannelGroup channelGroup;
	private final RegistryStorage registryStorage;

	public WatchRegistryHandler(RegistryChannelGroup channelGroup, RegistryStorage registryStorage)
	{
		this.channelGroup = channelGroup;
		this.registryStorage = registryStorage;
	}

	@Override
	public void handle(RegistryMessage message, Channel channel)
	{
		if (message.getNameSet().isEmpty())
			throw new RegistryStorageException("name is empty");

		for (String name : message.getNameSet())
		{
			channelGroup.watchChannel(name, channel);
			RegistryMessage response = message.success();
			response.clearName();
			response.addName(name);
			response.addItemList(registryStorage.list(name));
			channel.writeAndFlush(response).addListener(new SenderListener(response));
		}
	}
}
